﻿using System;
using System.IO;
using System.Windows.Forms;

namespace Chatclient
{
	public partial class FormHistory : Form
	{
		private PrivateChatMembers chatMembers;
		public FormHistory(PrivateChatMembers chatMembers)
		{
			this.chatMembers = chatMembers;
			InitializeComponent();
			this.Text = "Historie " + chatMembers.PrintUsers();
		}

		private void FormHistory_Load(object sender, System.EventArgs e)
		{
			LoadHistory();
		}

		private void LoadHistory()
		{
			string path = @"history/" + chatMembers.ThisUser + "/" + chatMembers.PrintUsers() + ".history";
			string[] lines = new string[0];
			if (File.Exists(path))
			{
				lines = File.ReadAllLines(path);
			}
			FillListView(lines);
		}

		private void FillListView(string[] lines)
		{
			foreach (var line in lines)
			{
				int firstUnderscorePosition = line.IndexOf('_');
				int secondUnderscorePosition = line.IndexOf('_', firstUnderscorePosition + 1);
				lstVwHistory.Items.Add(
					new ListViewItem(
						new string[] { line.Substring(0, firstUnderscorePosition), line.Substring(firstUnderscorePosition + 1, secondUnderscorePosition - firstUnderscorePosition - 1), line.Substring(secondUnderscorePosition + 1) }));
			}
		}

		private void FormHistory_SizeChanged(object sender, System.EventArgs e)
		{
			SetListViewColumnWidths();
		}

		/// <summary>
		/// Füllt die Spalten auf die komplette Breite der ListView unter Beibehaltung der Proportionen aus.
		/// </summary>
		private void SetListViewColumnWidths()
		{
			int listWidthNew = lstVwHistory.Width - 4;
			double listWidthOld = clmHdrDateTime.Width + clmHdrUser.Width + clmHdrText.Width;
			double clmDatWidth = clmHdrDateTime.Width / listWidthOld;
			double clmIntWidth = clmHdrUser.Width / listWidthOld;
			double clmTitWidth = clmHdrText.Width / listWidthOld;

			clmHdrDateTime.Width = (int)(listWidthNew * clmDatWidth);
			clmHdrUser.Width = (int)(listWidthNew * clmIntWidth);
			clmHdrText.Width = (int)(listWidthNew * clmTitWidth);
		}

		private void lstVwHistory_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (lstVwHistory.SelectedItems.Count > 0)
			{
				txtBxHistory.Clear();
				var items = lstVwHistory.SelectedItems[0].SubItems;
				txtBxHistory.Text = items[0].Text + Environment.NewLine + items[1].Text + Environment.NewLine + items[2].Text;
			}
		}
	}
}
